<?php
namespace ImiApp\Module\Member\Service;

// use Imi\Bean\Annotation\Bean;
use Imi\Server\Session\Session;
use ImiApp\Exception\BusinessException;
use ImiApp\Module\Member\Model\ScJigouTeam;
use ImiApp\Exception\NotFoundException;

use Imi\Db\Db;

// /**
//  * @Bean("TeamService")
//  */
class TeamService
{
    /**
     * 使用用户ID获取记录
     *
     * @param integer $id
     * @return \ImiApp\Module\Member\Model\ScJigouTeam
     */
    public function get(int $id): ScJigouTeam
    {
        var_dump('Team_ID',$id);

        $record = ScJigouTeam::find($id);
        if(!$record)
        {
            throw new NotFoundException(sprintf('未找到班级id： %s', $id));
        }
        return $record;
    }



    /**
     * 获取用户是否在某个班级里面
     *
     * @param int $uid 学生id
     * @param int $team_id 班级id
     * @return bool
     */
    public function getUid_is_team($uid,$team_id)
    {
        $db = Db::query()->table('sc_jigou_team_list');
        $res = $db->where('uid','=',$uid)->where('team_id','=',$team_id)->select();
        $team = $res->get();
        if($team){
            var_dump("该用户存在该班级".$team_id,$team);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取该班级的学生列表
     *
     * @param int $team_id 班级id
     * @return array
     */
    public function getTeamStudent(int $team_id): ScUser
    {
        $record = ScUser::find([
            'username'  =>  $username,
        ]);
        if(!$record)
        {
            throw new NotFoundException(sprintf('未找到用户 %s', $username));
        }
        return $record;
    }
  
    /**
     * 注册
     *
     * @param string $username
     * @param string $password
     * @return void
     */
    public function register(string $username, string $password)
    {
        try {
            $this->getByUsername($username);
            throw new BusinessException('该用户已被注册');
        } catch(NotFoundException $ne) {

        }
        $record = ScUser::newInstance();
        $record->username = $username;
        $record->password = password_hash($password, PASSWORD_BCRYPT);
        $record->save();
    }

    /**
     * 登录
     *
     * @param string $username
     * @param string $password
     * @return void
     */
    public function login(string $username, string $password)
    {
        $record = $this->getByUsername($username);
        if(password_verify($password, $record->password))
        {
            $record->lastLoginTime = date('Y-m-d H:i:s');
            $record->save();
            Session::set('memberId', $record->id);
        }
        else
        {
            throw new BusinessException('登录失败');
        }
    }

}
